import React from 'react';
import classnames from 'classnames';
import css from './index.less';
import reqwest from 'reqwest';
import { Input, InputNumber, Form, Modal, Table, Alert, Button, Col, message } from 'antd';
const InputGroup = Input.Group;
import { observer, inject, action } from 'mobx-react';
import config from '../../../../store/config.js'

@inject('store')
@observer
class GoodsModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      showWarn: false,
      confirmLoading: false,
      hasSelectGoods: props.modalData,
      peopleStart: props.palace.p_peopleStart || '',
      peopleEnd: props.palace.p_peopleEnd || '',
      crowdStart: props.palace.p_crowdStart || '',
      crowdEnd: props.palace.p_crowdEnd || '',
      allGoods: [],
      descType: 0
    };
    this.selected = [];
    this.allGoodsTotal = 0;
  }

  componentWillReceiveProps(nextProps) {
    //console.log(nextProps);
    this.setState({
      palace: nextProps.palace,
      visible: nextProps.modalType !== 0,
      hasSelectGoods: nextProps.modalData,
      peopleStart: nextProps.palace.p_peopleStart,
      peopleEnd: nextProps.palace.p_peopleEnd,
      crowdStart: nextProps.palace.p_crowdStart,
      crowdEnd: nextProps.palace.p_crowdEnd,
    });
    if(!this.state.allGoods.length) {
      this.getAllGoods({}, (data) => {
        console.log('datat', data);
        this.setState({
          allGoods: data.items.item
        });
        this.allGoodsTotal = data.total_results
      })
    }
  }

  getAllGoods(data, cb = () => {}) {
    //console.log(this.props.store);
    reqwest({
      url: config.serverUrl +'goods.do/getAllGoodsList',
      method: 'post',
      data:{
        code: this.props.store.loginCode,
        ...data
      },
      success: (data) => {
        cb(data)
      },
      error: (err) => {
        console.log('err: ', err);
      }
    })
  }

  hasGoodsColumns = [{
    title: '商品编号',
    dataIndex: 'g_num'
  },{
    title: '商品名称',
    dataIndex: 'g_title',
    render: text => <a href="#">{text}</a>
  }, {
    title: '商品价格',
    dataIndex: 'g_price'
  },{
    title: '操作',
    render: (text, record) => (
      <div>
        <a onClick={this.delGoods.bind(this, record)}>删除</a>
      </div>
    )
  }];

  allGoodsColumns = [{
    title: '商品编号',
    dataIndex: 'num_iid'
  },{
    title: '商品名称',
    dataIndex: 'title',
    render: text => <a href="#">{text}</a>
  }, {
    title: '商品价格',
    dataIndex: 'price'
  },{
    title: '操作',
    render: (text, record) => {
      const { hasSelectGoods } = this.state;
      let component = null;
      hasSelectGoods.forEach(item => {
        if(item.g_num == record.num_iid) {
          component = <div><span>已添加</span></div>;
        }
      });
      return component ||
        <div>
          <a onClick={this.addGoods.bind(this, record)}>添加</a>
        </div>;
    }
  }];

  addGoods(record) {
    const { hasSelectGoods } = this.state;
    //console.log('hasSelectGoods', hasSelectGoods);
    //console.log('record', record);
    if(hasSelectGoods.length <= 20) {
      hasSelectGoods.push({
        g_num: record.num_iid,
        g_title: record.title,
        g_price: record.price,
        g_imgUrl: record.pic_url
      });
      this.setState({
        hasSelectGoods
      });
    } else {
      message.error('每个宫殿最多只能选择20个商品，请删除一些在尝试！', 5)
    }

  }

  delGoods(record) {
    const { hasSelectGoods } = this.state;
    const newGoodsList = [].concat(hasSelectGoods);
    const index = newGoodsList.indexOf(record);
    newGoodsList.splice(index, 1);
    this.setState({
      hasSelectGoods: newGoodsList
    })
  }

  handleOk() {
    const { modalType, changeGoods = () => {}, changPalace = () => {} } = this.props;
    const { hasSelectGoods, peopleStart, peopleEnd, crowdStart, crowdEnd } = this.state;
      this.setState({confirmLoading: true});
      const that = this;
      Modal.confirm({
        title: 'Confirm',
        content: '您确认提交您的修改数据么？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          if(modalType === 1) {changeGoods(hasSelectGoods);}
          if(modalType === 2){
            changPalace(peopleStart, peopleEnd, crowdStart, crowdEnd)
          }
          that.setState({
            confirmLoading: false,
            visible: false
          });
        },
        onCancel() {
          that.setState({
            confirmLoading: false
          });
        }
      });
  };

  handleCancel()  {
    this.setState({
      visible: false
    });
  };

  onInputChange(value, type) {
    console.log(value, type);
    this.setState((state) => {
      state[type] = value;
    });
  }

  changDesc(index) {
    const { descType } = this.state;
    if(descType != index) {
      this.setState({
        descType: index
      });
      const descArr = ['list_time:desc', 'num:desc', 'modified:desc', 'sold_quantity:desc'];
      this.getAllGoods({
        "q": this.refs.search.refs.input.value,
        "order_by": descArr[index]
      },(data) => {
        console.log('data', data);
        this.setState({
          allGoods: data.items.item
        });
        this.allGoodsTotal = data.total_results
      })
    }
  }

  search() {
    const { descType } = this.state;
    const descArr = ['list_time:desc', 'num:desc', 'modified:desc', 'sold_quantity:desc'];
    this.getAllGoods({
      "q": this.refs.search.refs.input.value,
      "order_by": descArr[descType]
    },(data) => {
      console.log('data', data);
      this.setState({
        allGoods: data.items.item
      });
      this.allGoodsTotal = data.total_results
    })
  }

  render() {
    const {
      visible, confirmLoading, allGoods, hasSelectGoods, peopleStart, peopleEnd, crowdStart, crowdEnd
      } = this.state;
    const { palace, modalType } = this.props;
    const { allGoodsTotal } = this;
    const modalProps = {
      title: palace && palace.p_name ? palace.p_name : '',
      visible,
      width: modalType === 1 ? 1024 : 520,
      confirmLoading,
      onOk: this.handleOk.bind(this),
      onCancel: this.handleCancel.bind(this)
    };
    return (
      <Modal {...modalProps}>
        <div className={css.editBox}>
          <InputGroup className={css.inuptBox} size="large">
            <Col span={4}>
              <h4>查询商品：</h4>
            </Col>
            <Col span={11}>
              <Input ref="search" placeholder="请输入查询商品的标题"  />
            </Col>
            <Col span={1}>
              <Button icon="search" size="large" onClick={this.search.bind(this)} >查询</Button>
            </Col>
          </InputGroup>
          <InputGroup className={css.inuptBox} size="large">
            <Col span={4}>
              <h4>排序方式：</h4>
            </Col>
            <Col span={16}>
              {
                ['上架时间', '商品数量', '最近修改时间', '商品销量'].map((item, index) => {
                  const { descType } = this.state;
                  const props = {
                    type: descType === index ? "primary" : null,
                    onClick: this.changDesc.bind(this, index)
                  };
                  return <Button {...props}>{item}</Button>
                })
              }
            </Col>
          </InputGroup>
        </div>
        <div className={css.layout}>

          <div className={css.tableBox}>
            <h3>所有商品</h3>
            <Table columns={this.allGoodsColumns} scroll={{ x: '100%', y: 400 }} pagination={{ pageSize: 50,total: allGoodsTotal }} dataSource={allGoods}/>
          </div>
          <div className={css.tableBox}>
            <h3>已选商品</h3>
            <Table columns={this.hasGoodsColumns} scroll={{ x: '100%', y: 400 }} pagination={{ pageSize: 50,total: allGoodsTotal }} dataSource={hasSelectGoods}/>
          </div>
        </div>
      </Modal>
    );
  }
}

export default GoodsModal;

